package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.ModelDeploymentContext;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.ModelDeploymentPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.FlowModelProcdef;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowModelProcdefRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.ResourcePersistRepository;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.impl.persistence.entity.ResourceEntityImpl;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author lilh
 * @date 2021/4/26 14:24
 */
@Component
public class SaveModelDeploymentJsonProcessor implements ModelDeploymentPostProcessor {

    @Autowired
    private ResourcePersistRepository resourcePersistRepository;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private FlowModelProcdefRepository flowModelProcdefRepository;

    @Override
    public void process(ModelDeploymentContext context) {
        supplementModelDeploy(context.getDeployId(), context.getModelId(), context.getProcessName(), context.getModelBytes());
    }

    private void supplementModelDeploy(String deploymentId, String modelId, String processName, byte[] modelBytes) {
        // 增加保存一条model信息用于前端画图
        ResourceEntityImpl resourceEntity = new ResourceEntityImpl();
        resourceEntity.setName(processName + ".json");
        resourceEntity.setBytes(modelBytes);
        resourceEntity.setDeploymentId(deploymentId);
        resourcePersistRepository.insert(resourceEntity);
        // 增加保存model与流程定义的关联
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        FlowModelProcdef modelProcdefInfo = new FlowModelProcdef();
        modelProcdefInfo.setModelId(modelId);
        modelProcdefInfo.setProcDefId(processDefinition.getId());
        flowModelProcdefRepository.insert(modelProcdefInfo);
    }
}
